<?php

namespace App\Http\Middleware;

use App\Model\EleRoof;
use App\Model\User;
use Closure;
use Redis;

class AuthenticateToken
{

    protected $except = [
        'auth/bank-auth',
    ];
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
            $redis = $this->_Redis();
            $pass_token = $request->header('token');
            $user = $request->header('name');
//            $salt = 'l7ExbAPH1vUFKbTDfpEv4tXWXlnErKu9';
//            $tamp = date('Ymd');
//            $str =  strtoupper($user.$tamp.$salt);
//            $to = md5($str);
            $key = 'token:'.$user.':'.$pass_token;
//            $result = $redis->get($key);
            if (!$redis->exists( $key)) {
                return $this->json(false, 'token error', "41111");
            }else{
                return $next($request);
            }
    }

    protected function _Redis()
    {
        $redis=new Redis();
        $redis->connect(config('app.redishost'),config('app.redisport'));
//        $redis->auth(config('app.redispwd'));
//        $redis->connect('120.26.220.134',config('app.redispost'));
        $redis->auth(config('app.redispwd'));
//        $redis->auth('lggtest');
        $redis->select(1);
        return $redis;
    }

    protected function json()
    {
        $args = func_get_args();
        $result = $args[0];
        if($result=='true'){

            $json = array('result' => array("status"=>$result,"errorCode"=>"","errorMsg"=>""));

            if (func_num_args() > 1) $json['content'] = $args[1];

        }else {
            $json = array("status"=>0,"error_msg"=>$args[1],"error_code"=>$args[2]);
        }
        return response()->json($json);
    }

}
